<template>
  <div>
    <el-upload
        :action="action"
        :multiple="multiple"
        :limit="limit"
        :on-success="handleSuccess"
        :on-error="handleError"
        :on-progress="handleProgress"
        :before-upload="beforeUpload"
        :headers="headers"
        :data="data"
        :accept="accept"
        :file-list="fileList"
        list-type="picture-card"
    >
      <template #trigger>
        <el-button type="warning">选择文件</el-button>
      </template>
      <template #tip>
        <div class="el-upload__tip">只能上传 {{ accept }} 文件，且不超过 {{ limit }} 个</div>
      </template>
    </el-upload>
    <!-- 显示上传进度 -->
    <el-progress v-if="uploading" :percentage="uploadPercentage" status="success"></el-progress>
  </div>
</template>

<script setup>
import {ref, defineProps, defineEmits} from 'vue';

const env = import.meta.env;
const action = env.VITE_API_URL + '/api/system.file/upload';
const headers = {
  Authorization: localStorage.getItem('token') || ''
};

// 定义组件的 props
const props = defineProps({
  multiple: {
    type: Boolean,
    default: false
  },
  limit: {
    type: Number,
    default: 1
  },
  accept: {
    type: String,
    default: 'image/*'
  },
  headers: {
    type: Object,
    default: () => ({})
  },
  data: {
    type: Object,
    default: () => ({})
  },
  fileList: {
    type: Array,
    default: () => []
  }
});

// 定义组件的 emits
const emits = defineEmits(['upload-success', 'upload-error']);

// 上传状态和进度相关的 ref
const uploading = ref(false);
const uploadPercentage = ref(0);

// 上传成功的处理函数
const handleSuccess = (response, file, fileList) => {
  uploading.value = false;
  emits('upload-success', response, file, fileList);
};

// 上传失败的处理函数
const handleError = (error, file, fileList) => {
  uploading.value = false;
  emits('upload-error', error, file, fileList);
};

// 上传进度的处理函数
const handleProgress = (event, file, fileList) => {
  uploading.value = true;
  uploadPercentage.value = event.percent;
};

// 上传前的处理函数
const beforeUpload = (file) => {
  return true;
};

</script>

<style scoped>
.el-upload__tip {
  margin-top: 8px;
  color: #999;
}
</style>
